package com.zhu.service.edu.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhu.commons.utils.BeanCopyUtils;
import com.zhu.service.edu.ThreadLocalService.CourseThreadLocal;
import com.zhu.service.edu.ThreadLocalService.VideoDeleteThreadLocal;
import com.zhu.service.edu.feign.AliyunVodFeign;
import com.zhu.service.edu.feign.MinioFeignService;
import com.zhu.service.edu.feign.OssFeignService;
import com.zhu.service.edu.mapper.*;
import com.zhu.service.edu.pojo.*;
import com.zhu.service.edu.pojo.dto.CourseVo;
import com.zhu.service.edu.pojo.vo.*;
import com.zhu.service.edu.service.IEduCourseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.C;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 课程 服务实现类
 * </p>
 *
 * @author zhu
 * @since 2022-07-04
 */
@Service
@Slf4j
@Transactional(rollbackFor = Exception.class)
public class EduCourseServiceImpl extends ServiceImpl<EduCourseMapper, EduCourse> implements IEduCourseService {
    @Autowired
    private EduCourseMapper courseMapper;
    @Autowired
    private EduCourseDescriptionMapper descriptionMapper;
    @Autowired
    private CourseThreadLocal courseThreadLocal;
    @Autowired
    private EduCommentMapper commentMapper;
    @Autowired
    private EduCourseCollectMapper courseCollectMapper;
    @Autowired
    private EduVideoMapper videoMapper;
    @Autowired
    private EduChapterMapper chapterMapper;
    /**
     * 保存课程信息
     * @param courseInfoVo
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String saveCourseInfo(CourseInfoVo courseInfoVo) {
        /**
         * 1.保存课程，保存课程description
         */
        EduCourse eduCourse = BeanCopyUtils.copyBean(courseInfoVo, EduCourse.class);
        eduCourse.setStatus(EduCourse.COURSE_DRAFT);
        courseMapper.insert(eduCourse);
        log.info("课程信息:{}",eduCourse);
        /**
         * 2.保存课程描述信息
         */
        EduCourseDescription  courseDescription=new EduCourseDescription();
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setId(eduCourse.getId());
        descriptionMapper.insert(courseDescription);
        String id = eduCourse.getId();
        if(id!=null){
            return id;
        }
        return null;
    }

    @Override
    public CourseInfoVo getCourseInfoById(String id) {
        EduCourse eduCourse = courseMapper.selectById(id);
        if(eduCourse==null){
            return null;
        }
        EduCourseDescription courseDescription = descriptionMapper.selectById(id);
        if(courseDescription==null){
            return  null;
        }
        CourseInfoVo courseInfoVo = BeanCopyUtils.copyBean(eduCourse, CourseInfoVo.class);
        courseInfoVo.setDescription(courseDescription.getDescription());
        return courseInfoVo;
    }

    /**
     * 更新课程信息
     * @param courseInfoVo
     * @return
     */
    @Override
    public boolean updateCourseInfoById(CourseInfoVo courseInfoVo) {
        int i=0,j=0;
        EduCourse eduCourse = BeanCopyUtils.copyBean(courseInfoVo, EduCourse.class);
        if(eduCourse!=null){
           j=courseMapper.updateById(eduCourse);

        }
        EduCourseDescription byId = descriptionMapper.selectById(courseInfoVo.getId());
        EduCourseDescription courseDescription =new EduCourseDescription();
        courseDescription.setId(courseInfoVo.getId());
        courseDescription.setDescription(courseInfoVo.getDescription());
        courseDescription.setGmtCreate(byId.getGmtCreate());
        System.out.println(courseDescription);
        i = descriptionMapper.updateById(courseDescription);

        if(i==1&&j==1){
            return  true;
        }
        return   false;
    }

    @Override
    public IPage<EduCourse> selectPage(Page<EduCourse> pageParam, CourseQueryVo courseQueryVo) {
        return null;
    }


    @Override
    public PageBean selectPages(Long currentPage, Long size, CourseQueryVo courseQueryVo) {
        Page<EduCourse> page=new Page<>(currentPage,size);
        IPage<EduCourse> eduCourseIPage=courseMapper.selectPages(page,courseQueryVo);
        PageBean pageBean=new PageBean(eduCourseIPage.getTotal(),eduCourseIPage.getRecords());
        return pageBean;
    }
 @Autowired
 private MinioFeignService minioFeignService;
@Autowired
private VideoDeleteThreadLocal videoDeleteThreadLocal;
@Autowired
private AliyunVodFeign aliyunVodFeign;
@Autowired
private OssFeignService ossFeignService;
    /**
     * 根据id删除课程
     * @param id
     * @return
     */
    @Override
    public boolean removeCourseById(String id) {
        //删除封面
        courseThreadLocal.deleteCover(courseMapper,minioFeignService,id,ossFeignService);
        //删除课程
         videoDeleteThreadLocal.deleteVideoByList(id,aliyunVodFeign,courseMapper,videoMapper);
        //根据courseId删除video
        LambdaQueryWrapper<EduVideo> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduVideo::getCourseId,id);
        videoMapper.delete(queryWrapper);
        //删除chapter(章节)
        LambdaQueryWrapper<EduChapter> queryWrapper1=new LambdaQueryWrapper<>();
        queryWrapper1.eq(EduChapter::getCourseId,id);
        chapterMapper.delete(queryWrapper1);
        //删除CourseDescription
        descriptionMapper.deleteById(id);
        //删除commont
        LambdaQueryWrapper<EduComment> queryWrapper2=new LambdaQueryWrapper<>();
        queryWrapper2.eq(EduComment::getCourseId,id);
        commentMapper.delete(queryWrapper2);
        //删除collect
        //删除commont
        LambdaQueryWrapper<EduCourseCollect> queryWrapper3=new LambdaQueryWrapper<>();
        queryWrapper3.eq(EduCourseCollect::getCourseId,id);
        courseCollectMapper.delete(queryWrapper3);
        //删除course
        int i = courseMapper.deleteById(id);
        if(i==1){
             return true;
        }
        return false;
    }

    /**
     * 根据id发布课程信息
     * @param id
     * @return
     */
    @Override
    public CoursePublishVo getCoursePublishById(String id) {
        return  courseMapper.getCoursePublishById(id);
    }

    /**
     * 发布课程
     * @param id
     * @return
     */
    @Override
    public Boolean publishCourse(String id) {
        EduCourse course=new EduCourse();
        course.setId(id);
        course.setStatus(EduCourse.COURSE_NORMAL);

        int i = courseMapper.updateById(course);
        if(i==1){
            return  true;
        }
      return false;
    }

    /**
     * 客户端 查询课程列表   SQL错误，不想写了换Lambda
     * @param courseFrontQueryVo
     * @return
     */
    @Override
    public List<EduCourse> selectFrontList(CourseFrontQueryVo courseFrontQueryVo) {
        List<EduCourse> courseList= courseMapper.selectFrontList(courseFrontQueryVo);
        return courseList;
    }

    @Override
    public List<EduCourse> selectFrontListS(CourseFrontQueryVo courseFrontQueryVo) {
        LambdaQueryWrapper<EduCourse> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduCourse::getStatus,"Normal");
        if(StringUtils.isNotEmpty(courseFrontQueryVo.getSubjectId())){
            queryWrapper.eq(EduCourse::getSubjectId,courseFrontQueryVo.getSubjectId());
        }
        if(StringUtils.isNotEmpty(courseFrontQueryVo.getSubjectParentId())){
            queryWrapper.eq(EduCourse::getSubjectParentId,courseFrontQueryVo.getSubjectParentId());
        }
        if (!StringUtils.isEmpty(courseFrontQueryVo.getBuyCountSort())) {
            queryWrapper.orderByDesc(EduCourse::getBuyCount);
        }
       if(StringUtils.isNotEmpty(courseFrontQueryVo.getPriceSort())){
           queryWrapper.orderByDesc(EduCourse::getPrice);
       }
        if(StringUtils.isNotEmpty(courseFrontQueryVo.getGmtCreateSort())){
            queryWrapper.orderByDesc(EduCourse::getGmtCreate);
        }
        List<EduCourse> courseList = courseMapper.selectList(queryWrapper);
        return courseList;
    }
//@Autowired
//private CourseThreadLocal courseThreadLocal;
    /**
     * 查询课程详细信息
     * @param id
     * @return
     */
    @Override
    public List<SubjectInfoFrontVo> findCourseIntro(String id) {
        long currentTimeMillis = System.currentTimeMillis();
        //浏览数+1 线程池实现
        courseThreadLocal.updateViewCount(courseMapper,id);
        List<SubjectInfoFrontVo> subjectInfoFrontVoList= courseMapper.findCourseIntro(id);
        long l = System.currentTimeMillis();
        log.info("方法执行时间(线程池)：{}",l-currentTimeMillis);
        return subjectInfoFrontVoList;
    }

    @Override
    public List<SubjectInfoFrontVo> findCourseIntro2(String id) {
        long currentTimeMillis = System.currentTimeMillis();
        //更新viewCount
        EduCourse course = courseMapper.selectById(id);
        Long viewCount = course.getViewCount();
        EduCourse course1=new EduCourse();
        course1.setViewCount(viewCount+1);
        LambdaQueryWrapper<EduCourse> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(EduCourse::getViewCount,viewCount);
        queryWrapper.eq(EduCourse::getId,id);
        courseMapper.update(course,queryWrapper);
        //查询
        List<SubjectInfoFrontVo> courseIntro = courseMapper.findCourseIntro(id);
        long l = System.currentTimeMillis();
        log.info("方法执行时间（非线程池）：{}",l-currentTimeMillis);
        return courseIntro;
    }
    @Autowired
    private RedisTemplate redisTemplate;
    //查询热门课程
    @Override
//    @Cacheable(key = "HotCourse",value = "selectHotCourse")
    public List<EduCourse> selectHotCourse() {
        List<EduCourse>  courseList=(List<EduCourse>)redisTemplate.opsForValue().get("courseList");
        if(courseList!=null){
            log.info("走了缓存");
            return courseList;
        }
        LambdaQueryWrapper<EduCourse> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(EduCourse::getVersion);
        queryWrapper.last(" limit 8 ");
        List<EduCourse> courseList2 = courseMapper.selectList(queryWrapper);
        redisTemplate.opsForValue().set("courseList",courseList2);
        log.info("走了数据库");
        return courseList2;
    }
    @Autowired
    private EduTeacherMapper teacherMapper;
    //查询热门教师
    //此处可以优化 查询教师名下课程最多的4人
    @Override
//    @Cacheable(key = "HotTeacher",value = "selectHotTeacher")
    public List<EduTeacher> selectHotTeacher() {
        List<EduTeacher>  teacherList=(List<EduTeacher>)redisTemplate.opsForValue().get("teacherList");
        if(teacherList!=null){
            log.info("走了缓存");
            return teacherList;
        }
        LambdaQueryWrapper<EduTeacher> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(EduTeacher::getSort);
        queryWrapper.last(" limit 4 ");
        List<EduTeacher> teacherList2 = teacherMapper.selectList(queryWrapper);
        redisTemplate.opsForValue().set("teacherList",teacherList2);
        return teacherList2;
    }

    @Override
    public CourseVo getCourseDtoById(String courseId) {
        EduCourse course = courseMapper.selectById(courseId);
        String teacherId = course.getTeacherId();
        EduTeacher eduTeacher = teacherMapper.selectById(teacherId);
        CourseVo courseVo=new CourseVo();
        courseVo.setId(course.getId());
        courseVo.setCover(course.getCover());
        courseVo.setPrice(course.getPrice());
        courseVo.setTitle(course.getTitle());
        courseVo.setTeacherName(eduTeacher.getName());
        return courseVo;
    }
}
